package com.snow.datasource.advisor;

import cn.hutool.core.util.StrUtil;
import com.snow.datasource.datasource.DynamicDataSourceContextHolder;
import com.snow.datasource.resolver.DataSourceClassResolver;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

/**
 * @Description
 * @Author fanxl
 * @Date 2020/12/17
 **/
public class SnowDataSourceAnnotationInterceptor implements MethodInterceptor {

    private DataSourceClassResolver dataSourceClassResolver;


    public SnowDataSourceAnnotationInterceptor(Boolean allowedPublicOnly) {
        dataSourceClassResolver = new DataSourceClassResolver(allowedPublicOnly);
    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        try {
            String dsKey = determineDatasourceKey(invocation);
            if (StrUtil.isNotEmpty(dsKey)){
                DynamicDataSourceContextHolder.push(dsKey);
            }
            return invocation.proceed();
        } finally {
            DynamicDataSourceContextHolder.poll();
        }
    }

    private String determineDatasourceKey(MethodInvocation invocation) {
        String key = dataSourceClassResolver.findDSKey(invocation.getMethod(), invocation.getThis());
        return key;
    }

}
